<template>
  <view>
    <!-- 个人信息显示 -->
    <view class="header_block">
      <!-- 头像 -->
      <img :src="personAvatar" alt="" class="user_avater" @click="changeAvatar">
      <view class="body_center">
        <span>真实姓名：{{ userInfo.staff.name }}</span>
        <view class="isCertify_cell" v-if="userInfo.staff.isCertify == 1">
          <span v-if="!!userInfo.staffCertification">实名认证时间：{{ userInfo.staffCertification.certifyTime }}</span>
          <span v-else>认证时间：--</span>
        </view>
      </view>
    </view>

    <uni-list>
      <uni-list-item :title="'个人账号：' + userInfo.staff.nickId" rightText="注销账户" clickable @click="logOff"/>
      <uni-list-item>
        <template v-slot:header>
          <span>证件号码：{{ userInfo.staff.idNumberHide }}</span>
        </template>
        <template v-slot:footer v-if="userInfo.staff.isCertify == 1">
		    <span
            v-if="userInfo.staffCertification.credentialStatus == 0"
            class="errorColor"
            @click="toCredentialPreview"
        >无效证件
		    </span>
          <span
              v-if="userInfo.staffCertification.credentialStatus == 1"
              class="themeColor"
              @click="toCredentialPreview"
          >查看证件
		    </span>
          <span
              v-if=" userInfo.staffCertification.credentialStatus== 2"
              class="errorColor"
              @click="toCredentialPreview"
          >证件审核中
		    </span>
          <span
              v-if="userInfo.staffCertification.credentialStatus == 3"
              class="errorColor"
              @click="toPerfectInfo"
          >请补传证件信息
		    </span>
          <span
              v-if="userInfo.staffCertification.credentialStatus == 4"
              class="errorColor"
              @click="toCredentialPreview"
          >证件已过期
		    </span>
        </template>
      </uni-list-item>
    </uni-list>

    <uni-list style="margin: 20rpx 0;">
      <view class="list-item" style="border-bottom: 1rpx solid #eee;">
        <p>账户余额：{{ (!!userInfo.staff.balance) ? userInfo.staff.balance : 0 }}元</p>
        <view>
          <view size="mini" class="optino_btn" @click="recharge">余额充值</view>
          <view size="mini" class="optino_btn" @click="balanceList" style="margin:0 80rpx;">余额明细</view>
          <view size="mini" class="optino_btn" @click="balanceDetailed">充值记录</view>
        </view>
      </view>

      <view class="list-item" style="border-bottom: 1rpx solid #eee;">
        <p>合同签署量：{{ !!userInfo.remainingNum ? userInfo.remainingNum : 0 }}次</p>
        <view>
          <view size="mini" class="optino_btn" @click="product">立即购买</view>
          <view size="mini" class="optino_btn" @click="signList" style="margin:0 80rpx;">签署明细</view>
          <view size="mini" class="optino_btn" @click="signRecord">签署套餐</view>
        </view>
      </view>

      <view class="list-item">
        <p>账户碳能量：{{ !!userInfo.staff.integral ? userInfo.staff.integral : 0 }}g</p>
        <view>
          <view size="mini" class="optino_btn" @click="product">兑换签署量</view>
          <view size="mini" class="optino_btn" @click="integralRecord" style="margin:0 60rpx;">碳能量明细</view>
          <view size="mini" class="optino_btn" @click="handleToWithdrawal">碳能量提现</view>
        </view>
      </view>
      <!-- 点击分享 -->
      <uni-list-item clickable title="分享1位实名注册企业，得2000碳能量！点击分享" @click="toShare"/>
    </uni-list>

    <uni-list>
      <!-- 手机号 -->
      <uni-list-item rightText="修改" @click="toModifyMobileDialog()" clickable>
        <template v-slot:body>
          <view class="slot-header">
            手机号：
            <span v-if="!!userInfo.staff.mobileHide">{{ userInfo.staff.mobileHide }}</span>
            <span v-else>--</span>
          </view>
        </template>
      </uni-list-item>
      <!-- 性别 -->
      <uni-list-item rightText="修改" @click="toShowModifySexDialog" clickable>
        <template v-slot:body>
          <view class="slot-header">
            性别：
            <template v-for="(item, index) in dicts.sys_user_sex">
              <template v-if="userInfo.staff.sex == item.value">
                <span>{{ item.text }}</span>
              </template>
            </template>
          </view>
        </template>
      </uni-list-item>
      <!-- 邮箱 -->
      <uni-list-item @click="toGetSmsCodeDialog(6)" clickable>
        <template v-slot:body>
          <view class="slot-header">
            <view v-if="userInfo.staff.email == null || userInfo.staff.email == ''">邮箱：未设置，设置后可通过邮箱接收合同</view>
            <view v-else>邮箱：{{ userInfo.staff.emailHide }}</view>
          </view>
        </template>
        <template v-slot:footer>
          <view v-if="userInfo.staff.email == null || userInfo.staff.email == ''" class="text_right">设置</view>
          <view v-else class="text_right">修改</view>
        </template>
      </uni-list-item>
      <!-- 登录密码 -->
      <uni-list-item @click="toGetSmsCodeDialog(6)" clickable>
        <template v-slot:body>
          <view class="slot-header">
            <span style="margin-right: 20rpx;">登录密码</span>
            <uni-tag v-if="!!userInfo.staff.password" type="success" text="已设置"/>
            <uni-tag type="error" v-else text="未设置"/>
          </view>
        </template>
        <template v-slot:footer>
          <view v-if="!!userInfo.staff.password" class="text_right">修改</view>
          <view v-else class="text_right">设置</view>
        </template>
      </uni-list-item>
      <!-- 签署密码、支付密码 -->
      <uni-list-item @click="toGetSmsCodeDialog(7)" clickable>
        <template v-slot:body>
          <view class="slot-header">
            <span style="margin-right: 20rpx;">签署密码 / 支付密码</span>
            <uni-tag type="success" v-if="!!userInfo.staff.payPassword" text="已设置"/>
            <uni-tag type="error" v-else text="未设置"/>
          </view>
        </template>
        <template v-slot:footer>
          <view v-if="!!userInfo.staff.payPassword" class="text_right">修改</view>
          <view v-else class="text_right">设置</view>
        </template>
      </uni-list-item>
      <!-- 微信绑定 -->
      <uni-list-item clickable>
        <template v-slot:body>
          <view class="slot-header">
            <span style="margin-right: 20rpx;">微信绑定</span>
            <uni-tag type="success" v-if="userInfo.staff.isCertify == 1" text="未设置"/>
            <uni-tag type="success" v-else text="未设置"/>
          </view>
        </template>
        <template v-slot:footer>
          <view v-if="userInfo.staff.isCertify == 1" class="text_right">解绑</view>
          <view v-else class="text_right">绑定</view>
        </template>
      </uni-list-item>
      <uni-list-item title="客户服务热线：400-891-3655" rightText="点击咨询" clickable @click="phone"/>
    </uni-list>

    <!-- 获取原始手机号码验证码 -->
    <get-sms-code ref="getSmsCode" @success="getSmsCodeSuccess"></get-sms-code>
    <!-- 修改手机号码 -->
    <modify-mobile ref="modifyMobile" @success="loginOutDialog"></modify-mobile>
    <!-- 修改性别 -->
    <modify-sex ref="modifySex" @success="findUserInfo"></modify-sex>
    <!-- 修改邮箱 -->
    <modify-email ref="modifyEmail" @success="findUserInfo"></modify-email>
    <!-- 修改登录密码 -->
    <modify-login-pwd ref="modifyLoginPwd" @success="loginOutDialog"></modify-login-pwd>
    <!-- 修改签署密码 -->
    <modify-sign-pwd ref="modifySignPwd"></modify-sign-pwd>
    <!-- 账户注销 -->
    <log-off ref="logOff"></log-off>

  </view>
</template>

<script>
import {getToken} from '@/utils/auth'
import config from '@/config'
import store from "@/store"
import {findUserInfo} from "@/api/ec/person/user/userInfo";
import {parseTime} from "@/utils/common";
import {getDictsByNameForUni} from "../../../../utils/dicts";

import modifyMobile from "./modifyMobile";
import modifySex from "./modifySex";
import modifyEmail from "./modifyEmail";
import getSmsCode from "./getSmsCode";
import modifyLoginPwd from "./modifyLoginPwd";
import modifySignPwd from "./modifySignPwd";
import logOff from "@/components/logOff/index"
import {isWebView, isWechat} from "../../../../utils/validate";

export default {
  components: {modifyMobile, modifySex, modifyEmail, getSmsCode, modifyLoginPwd, modifySignPwd, logOff},
  data() {
    return {
      // 数据字典
      dicts: {
        // 性别
        sys_user_sex: [],
      },
      // host地址
      host: config.baseUrl,
      //用户信息
      userInfo: {staff: {name: ''}},
      // 个人默认头像
      personAvatar: require("@/static/images/personal-info.png"),
    }
  },
  onLoad() {
    this.getDicts()
    this.bindingRefreshData();
  },
  onUnload() {
    this.unbindingRefreshData();
  },
  created() {
    this.findUserInfo();
  },
  methods: {
    // ===============================================================================================================
    // ==== 加载数据字典
    // ===============================================================================================================
    /**加载数据字典*/
    getDicts() {
      // 性别
      this.dicts.sys_user_sex = getDictsByNameForUni("sys_user_sex");
    },
    /** 绑定 */
    bindingRefreshData() {
      // 刷新页面数据
      uni.$on('refreshUserInfoData', () => {
        this.findUserInfo();
      });
      // 头像图片剪切成功
      uni.$on('userInfoCropperSuccess', (base64, type) => {
        this.cropperSuccess(base64, type);
      });
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('userInfoCropperSuccess');
    },
    // =================================================================================================================
    // ==== 页面跳转
    // =================================================================================================================
    /** 碳能量明细 */
    integralRecord() {
      this.$tab.navigateTo('/pages/mine/signFlowFeeOrder/integralRecord/integralRecord')
    },
    /** 签署明细 */
    signList() {
      this.$tab.navigateTo('/pages/mine/signFlowFeeOrder/signFlowFeeRecord/signFlowFeeRecord')
    },
    /** 立即购买 */
    product() {
      this.$tab.navigateTo('/pages/mine/personal/product/index')
    },
    /** 签署记录 */
    signRecord() {
      this.$tab.navigateTo('/pages/mine/signFlowFeeOrder/index')
    },
    /** 余额明细 */
    balanceList() {
      this.$tab.navigateTo('/pages/mine/signFlowFeeOrder/balance/personBalance')
    },
    /** 余额充值-个人-资料 */
    recharge() {
      this.$goPay();
    },
    /** 充值记录 */
    balanceDetailed() {
      this.$tab.navigateTo('/pages/mine/personal/product/balancePay/index')
    },
    /** 拨打电话 */
    phone() {
      uni.makePhoneCall({phoneNumber: '400-891-3655'});
    },
    /** 账户注销 */
    logOff() {
      this.$refs.logOff.openDialog()
    },
    /** 点击分享 */
    toShare() {
      this.$tab.navigateTo('/pages/mine/personal/share/shareUrl')
    },
    /** 查看证件信息 */
    toCredentialPreview() {
      uni.navigateTo({url: './credentialPreview?staffCertification=' + encodeURIComponent(JSON.stringify(this.userInfo.staffCertification))});
    },
    /** 请补传证件信息 */
    toPerfectInfo() {
      this.$tab.navigateTo('./perfectInfo')
    },
    /** 立即提现  */
    handleToWithdrawal() {
      if (this.userInfo.staffCertification.credentialStatus == 1) {
        // 到提现页面
        this.$tab.navigateTo('/pages/mine/personal/personalCenter/cashOut/index')
      } else if (this.userInfo.staffCertification.credentialStatus == 2) {
        this.$modal.msgError("您的证件正在审核中，暂无法提现！");
        setTimeout(() => {
          this.toCredentialPreview();
        }, 500);
      } else {
        // 其他完善证件
        this.toPerfectInfo();
      }
    },
    // =================================================================================================================
    // ==== 获取账户基本信息
    // =================================================================================================================
    /** 账户信息 */
    findUserInfo() {
      this.$modal.loading();
      findUserInfo().then(response => {
        uni.hideLoading()
        this.userInfo = response.data;
        // 证件图片
        this.userInfo.staffCertification.idCardFrontImg = (!!this.userInfo.staffCertification.idCardFrontImg) ? "data:image/png;base64," + this.userInfo.staffCertification.idCardFrontImg : null;
        this.userInfo.staffCertification.idCardBackImg = (!!this.userInfo.staffCertification.idCardBackImg) ? "data:image/png;base64," + this.userInfo.staffCertification.idCardBackImg : null;
        // 签署套餐最近到期时间
        this.userInfo.remainingExpiration = parseTime(this.userInfo.remainingExpiration)
        // 头像
        this.personAvatar = (this.userInfo.staff.avatar == "" || this.userInfo.staff.avatar == null) ? this.personAvatar : this.host + this.userInfo.staff.avatar;
      }).catch(() => {
        uni.hideLoading()
      });
    },
    // =================================================================================================================
    // ==== 修改头像
    // =================================================================================================================
    /** 修改头像 */
    changeAvatar() {
      uni.navigateTo({url: "/pages/common/imageCropper/index?callbackMethod=userInfoCropperSuccess&width=200&height=200&imageSrc=" + encodeURIComponent(this.personAvatar)});
    },
    /** 用户头像图片剪切成功回调方法，上传头像 */
    cropperSuccess(base64, type) {
      // Base64字符串转二进制流
      let arrayBuffer = uni.base64ToArrayBuffer(base64.replace(/^data:image\/\w+;base64,/, ""))
      // 二进制流转blob
      let blob = new Blob([arrayBuffer], {type: "image/png"});
      uni.uploadFile({
        url: this.host + "/person/userInfo/avatar",
        file: blob,
        header: {
          'Authorization': 'Bearer ' + getToken(),
        },
        name: 'avatarfile',
        success: (res) => {
          let data = JSON.parse(res.data);
          this.personAvatar = this.host + data.imgUrl;
          // 更新头像地址缓存
          store.commit('SET_AVATAR', data.imgUrl);
          let staffInfo = this.$store.getters.staffInfo;
          // 更新用户信息缓存
          staffInfo.avatar = data.imgUrl;
          store.commit('SET_USER', staffInfo);
          uni.showToast({title: "修改成功", icon: 'success'})
        }
      });
    },
    // =================================================================================================================
    // ==== 获取账户基本信息修改
    // =================================================================================================================
    /** 原始手机号码获取短信验证码 */
    toGetSmsCodeDialog(smsType) {
		if(smsType == 6 && !this.userInfo.staff.password){
			this.$refs.modifyLoginPwd.toOpenDialog(this.userInfo.staff, '');
		}else if(smsType == 7 && !this.userInfo.staff.payPassword){
			this.$refs.modifySignPwd.toOpenDialog(this.userInfo.staff, '');
		}else{
			this.$refs.getSmsCode.toOpenDialog(this.userInfo.staff, smsType);
		}
    },
    /** 修改手机号 */
    toModifyMobileDialog() {
      this.$refs.modifyMobile.toOpenDialog(this.userInfo.staff);
    },
    /** 修改性别 */
    toShowModifySexDialog() {
      this.$refs.modifySex.toOpenDialog(this.userInfo.staff);
    },
    /** 修改邮箱 */
    toShowModifyEmailDialog() {
      this.$refs.modifyEmail.toOpenDialog(this.userInfo.staff);
    },
    /** 原始手机号码获取短信验证码成功回调 */
    getSmsCodeSuccess(smsType, smsCode) {
      if (smsType == 6) {
        // 修改登录密码
        this.$refs.modifyLoginPwd.toOpenDialog(this.userInfo.staff, smsCode);
      } else if (smsType == 7) {
        // 修改签署密码
        this.$refs.modifySignPwd.toOpenDialog(this.userInfo.staff, smsCode);
      }
    },
    /** 弹出退出系统提示 */
    loginOutDialog() {
      let _this = this
      uni.showModal({
        title: '系统提示',
        confirmColor: '#00a660',
        confirmText: '确定',
        content: '修改登录密码成功，您需要重新登录!',
        success: function (res) {
          if (res.confirm) {
            _this.$store.dispatch('LogOut').then(() => {
              uni.reLaunch({url: '/pages/index'});
            })
          }
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .uni-list-item--hover {
  background: none;
}

.certify-time {
  margin-top: 8rpx;
  display: flex;
  justify-content: space-between;

  view {
    color: #999;
    font-size: 26rpx;
  }
}

.optino_btn {
  display: inline-block;
  background: #e6f6ef;
  color: $uni-color-primary;
  borde: 1rpx solid #99dbbf;
  padding: 10rpx 30rpx;
  font-size: 24rpx;
  margin-top: 30rpx;
  border-radius: 6rpx;
}

.list-item {
  padding: 20rpx 40rpx;
}

.idCard-text {
  span {
    font-size: 26rpx;
  }
}

.slot-header {
  width: 91.5%;
}

.smscode_flex {
  display: flex;
  align-items: center;
  margin-top: 15rpx;

  .code_btn {
    background: $uni-color-primary;
    color: #fff;
    padding: 4rpx 0;
    width: 170rpx;
    font-size: 26rpx;
    margin-left: 10rpx;
  }

  .code_graybtn {
    background: #cccccc;
    color: #fff;
    padding: 4rpx 0;
    width: 170rpx;
    font-size: 26rpx;
    margin-left: 10rpx;
  }
}

::v-deep .uni-dialog-content {
  display: block;
}

.text_right {
  font-size: 26rpx !important;
  color: #999999;
}

::v-deep .uni-list-item {
  font-size: 28rpx;
  padding: 3rpx 10rpx;
}

::v-deep .uni-list-item__extra-text {
  display: flex;
  justify-content: flex-end;
  font-size: 26rpx;
}

.header_block {
  display: flex;
  align-items: center;
  padding: 20rpx 40rpx 20rpx 30rpx;
  background: #e6f6ef;

  .body_center {
    font-size: 30rpx;
    margin-left: 20rpx;
    width: 62%;
  }

  // 注销账户
  .cancellation {
    color: red;
    font-size: 26rpx;
  }

  // 头像
  .user_avater {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
  }

  .isCertify_cell {
    font-size: 24rpx;
    color: #888888;
    margin: 6rpx 0;
  }
}

.row_text {
  display: flex;
  justify-content: space-between;
  padding: 6rpx 0;
  font-size: 28rpx;

  span:last-child {
    color: $uni-color-primary;
    font-size: 26rpx;
  }
}
</style>
